﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Mappings;
using System.Xml.Serialization;
using NHibernate.Mapping;

namespace Apollo
{
    [Serializable]
    [NHibernateEntity(Table = "apl_Entities")]
    public class Entity
    {
        public Entity() { }

        [PrimaryKey]
        public virtual int Id { get; set; }

        [Property]
        public virtual string Name { get; set; }

        [Property]
        public virtual string DisplayProperty { get; set; }

        [Property]
        public virtual string IdentifierProperty { get; set; }

        [Property]
        public virtual string IconPath { get; set; }

        [Property]
        public virtual string Type { get; set; }

        [Property]
        public virtual string Filter { get; set; }

        [XmlIgnore]
        [BelongsTo(Column = "ID_Default_EntityView")]
        public virtual EntityView DefaultView { get; set; }

        [XmlIgnore]
        [BelongsTo(Column = "ID_Default_EntityEdit")]
        public virtual EntityEdit DefaultEdit { get; set; }

        [Property]
        public virtual string CustomViewUrl { get; set; }

        [Property]
        public virtual string CustomEditUrl { get; set; }

        [Property]
        public virtual EntityLoading Loading { get; set; }


        protected PersistentClass persistent;
        public virtual PersistentClass PersistentClass { get { 
            if(persistent == null)
                persistent = Apollo.Application.Configuration.ClassMappings
                    .Single<PersistentClass>(p => p.MappedClass.Name == this.Name);

            return persistent;
        } }

        public virtual Type MappedClass { get { return this.PersistentClass.MappedClass; } }

        public virtual string CurrentFilter { get {
            try {
                EntityFilter ef = Application.Meta<EntityFilter>()
                    .Where(e => e.Entity.Id == this.Id && e.Role.Id == Application.CurrentUser.Role.Id)
                    .SingleOrDefault();

                if (ef != null && !string.IsNullOrEmpty(ef.Filter)) {
                    if (!string.IsNullOrEmpty(this.Filter))
                        return "{groupOp:\"AND\",groups:["+this.Filter+","+ef.Filter+"],rules:[]}";
                    else
                        return ef.Filter;
                }

                return null;
            }
            catch(Exception ex) {
                Exception nex = new Exception("Failed to load filter for entity \"" + this.Name + "\" by user \"" + Application.CurrentUser.Name + "\"", ex);

                Application.LogError(nex);

                throw nex;

                //return this.Filter; 
            }
        } }


    }

    public enum EntityLoading { 
        Normal = 0,
        LowLoading = 1,
        HeavyLoading = 2
    }
}
